//
//  LZCartViewController.m
//  LZCartViewController
//
//  Created by LQQ on 16/5/18.
//  Copyright © 2016年 LQQ. All rights reserved.
//  https://github.com/LQQZYY/CartDemo
//  http://blog.csdn.net/lqq200912408
//  QQ交流: 302934443

#import "LZCartViewController.h"
#import "LZConfigFile.h"
#import "LZCartTableViewCell.h"
#import "LZShopModel.h"
#import "LZGoodsModel.h"
#import "LZTableHeaderView.h"
#import "CustomGgThirdView.h"
#import "FenLeiSelectListModle.h"
#import "FenLeiExistListModle.h"
#import "FenLeiDDetailViewController.h"


#import "TiJIaoDingDanViewController.h"//结算

@interface LZCartViewController ()<UITableViewDelegate,UITableViewDataSource,customGgThirdViewDelegate>
{
    BOOL _isHiddenNavigationBarWhenDisappear;//记录当页面消失时是否需要隐藏系统导航
    BOOL _isHasTabBarController;//是否含有tabbar
    BOOL _isHasNavitationController;//是否含有导航
    
    BOOL flageCount;//数量加减按钮的显示与消失
    NSString *oldChooseID;
    
    
}

@property (strong,nonatomic)NSMutableArray *dataArray;
@property (strong,nonatomic)NSMutableArray *selectedArray;
@property (strong,nonatomic)UITableView *myTableView;
@property (strong,nonatomic)UIButton *allSellectedButton;
@property (strong,nonatomic)UILabel *totlePriceLabel;
@property (nonatomic, strong)UIButton *editOrCompleteBtn;


@property (nonatomic, strong)CustomGgThirdView *customThirdView;//弹出规格视图


@property (nonatomic, strong)NSMutableArray *guigeArray;//后台返回的规格选择数组
//@property (nonatomic, strong)NSDictionary *moRenChooseDic;//默认选中的规格
@property (nonatomic, strong) FenLeiExistListModle *morenModle;

@property (nonatomic, strong)NSMutableArray *numsKindArray;//各种拼凑可能含有的情况


@end

@implementation LZCartViewController

#pragma mark - viewController life cicle

- (void)viewWillAppear:(BOOL)animated {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    if (_isHasNavitationController == YES) {
        if (self.navigationController.navigationBarHidden == YES) {
            _isHiddenNavigationBarWhenDisappear = NO;
        } else {
            self.navigationController.navigationBarHidden = YES;
            _isHiddenNavigationBarWhenDisappear = YES;
        }
    }
    
    
    //当进入购物车的时候判断是否有已选择的商品,有就清空
    //主要是提交订单后再返回到购物车,如果不清空,还会显示
  
    if (self.selectedArray.count > 0) {
        for (LZGoodsModel *model in self.selectedArray) {
            model.select = YES;//这个其实有点多余,提交订单后的数据源不会包含这些,保险起见,加上了
        }
       // [self.selectedArray removeAllObjects];
    }
}

-(void)creatData {
 
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(Shop_CartGetCartList) parameters:parameDic success:^(id responseObject) {
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"获取购物车数据出错" timeLength:1.5];
            return ;
        }
        
        NSLog(@"-=-=--%@",responseObject);
    
        if (_dataArray) {
            [_dataArray removeAllObjects];
        }
        NSArray *array = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
        if (array.count > 0) {
            for (NSDictionary *dic in array) {
                LZShopModel *model = [[LZShopModel alloc]init];
                model.shopID = [[dic objectForKey:@"shop_data"] objectForKey:@"m_id"];
                model.shopName = [[dic objectForKey:@"shop_data"]objectForKey:@"shop_name"];
                model.sID = [[dic objectForKey:@"shop_data"] objectForKey:@"m_id"];
                
                model.sku_weight = [dic objectForKey:@"all_sku_weight"];
                [model configGoodsArrayWithArray:[dic objectForKey:@"sku_list"]];
                
                [self.dataArray addObject:model];
            }
        }
        [self.myTableView reloadData];
        if (self.dataArray.count > 0) {
            [self setupCartView];
        } else {
            [self setupCartEmptyView];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)loadData {
    [self creatData];
    [self changeView];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _isHasTabBarController = self.tabBarController?YES:NO;
    _isHasNavitationController = self.navigationController?YES:NO;
    
#warning 模仿请求数据,延迟2s加载数据,实际使用时请移除更换
    //[self performSelector:@selector(loadData) withObject:nil afterDelay:3];
    [self loadData];
    
    [self setupCustomNavigationBar];
    
    
    
//建立通知，用来监听如果有薪的商品加入购物车，则舒心购物车
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refshIngShopCar) name:@"refshIngShopCar" object:nil];
    

}
- (void)refshIngShopCar {
    [self loadData];
}
/*
#pragma mark  上啦家在下拉刷新
- (void)handleRefresh { //刷新
    [self loadData];
}

- (void)handleLoadMore {  //加载更多
    NSLog(@"加载更多");
    
}
 */
- (void)viewWillDisappear:(BOOL)animated {
    if (_isHiddenNavigationBarWhenDisappear == YES) {
        self.navigationController.navigationBarHidden = NO;
    }
}

/**
 *  @author LQQ, 16-02-18 11:02:16
 *
 *  计算已选中商品金额
 */
-(void)countPrice {
    double totlePrice = 0.0;
    
    for (LZGoodsModel *model in self.selectedArray) {
        
        double price = [model.price doubleValue];
        
        totlePrice += price * model.count;
    }
    NSString *string = [NSString stringWithFormat:@"￥%.2f",totlePrice];
    self.totlePriceLabel.attributedText = [self LZSetString:string];
}




#pragma mark - 初始化数组
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _dataArray;
}

- (NSMutableArray *)selectedArray {
    if (_selectedArray == nil) {
        _selectedArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _selectedArray;
}

#pragma mark - 布局页面视图
#pragma mark -- 自定义导航
- (void)setupCustomNavigationBar {
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LZSCREEN_WIDTH, LZNaigationBarHeight)];
    backgroundView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backgroundView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, LZNaigationBarHeight - 0.5, LZSCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = KShouYeBg;
    [self.view addSubview:lineView];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"购物车";
    titleLabel.font = [UIFont systemFontOfSize:20];
    
    titleLabel.center = CGPointMake(self.view.center.x, (LZNaigationBarHeight - 20)/2.0 + 20);
    CGSize size = [titleLabel sizeThatFits:CGSizeMake(300, 44)];
    titleLabel.bounds = CGRectMake(0, 0, size.width + 20, size.height);
    
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];

  
    UIButton *messageBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    messageBtn.frame = CGRectMake(kScreen_Width- 45, CGRectGetMinY(titleLabel.frame), 30, 30);
    [messageBtn setImage:[UIImage imageNamed:@"fenlei_xiaoxi"] forState:(UIControlStateNormal)];
    [self.view addSubview:messageBtn];
    
    
    
    UIButton *editBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    editBtn.frame = CGRectMake(CGRectGetMinX(messageBtn.frame)-60, CGRectGetMinY(titleLabel.frame), 50, 30);
    editBtn.titleLabel.font = kFont16;
    [editBtn setTitle:@"编辑" forState:(UIControlStateNormal)];
    [editBtn setTitle:@"完成" forState:(UIControlStateSelected)];
    [editBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    
    [editBtn addTarget:self action:@selector(handleEditOrCompleteAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:editBtn];
    
    
    
}
#pragma  mark  --=-=-=编辑按钮的点击事件
//编辑按钮或者完成按钮
- (void)handleEditOrCompleteAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    //编辑状态
    if (sender.selected == YES) {
          _editOrCompleteBtn.hidden = NO;
        self.totlePriceLabel.hidden = YES;
        
        
    }
    //完成状态
    else {
        _editOrCompleteBtn.hidden = YES;
        self.totlePriceLabel.hidden = NO;
        
    }

    
    
}

#pragma mark -- 自定义底部视图 
- (void)setupCustomBottomView {
    
    UIView *backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = KShouYeBg;
    backgroundView.tag = TAG_CartEmptyView + 1;
    [self.view addSubview:backgroundView];
    
    //当有tabBarController时,在tabBar的上面
    if (_isHasTabBarController == YES) {
        backgroundView.frame = CGRectMake(0, LZSCREEN_HEIGHT -  2*LZTabBarHeight, LZSCREEN_WIDTH, LZTabBarHeight);
    } else {
        backgroundView.frame = CGRectMake(0, LZSCREEN_HEIGHT -  LZTabBarHeight, LZSCREEN_WIDTH, LZTabBarHeight);
    }

    //全选按钮
    UIButton *selectAll = [UIButton buttonWithType:UIButtonTypeCustom];
    selectAll.titleLabel.font = [UIFont systemFontOfSize:16];
    selectAll.frame = CGRectMake(0, 5, 80, LZTabBarHeight - 10);
    [selectAll setTitle:@" 全选" forState:UIControlStateNormal];
    [selectAll setImage:[UIImage imageNamed:lz_Bottom_UnSelectButtonString] forState:UIControlStateNormal];
    [selectAll setImage:[UIImage imageNamed:lz_Bottom_SelectButtonString] forState:UIControlStateSelected];
    [selectAll setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [selectAll addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:selectAll];
    self.allSellectedButton = selectAll;
    
    //结算按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"bg1"] forState:(UIControlStateNormal)];
    btn.frame = CGRectMake(LZSCREEN_WIDTH - 120, 0, 120, LZTabBarHeight);
    [btn setTitle:@"结算" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(goToPayButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:btn];
    
    
  
    
    
    
    //合计
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = KQiangGour;
    [backgroundView addSubview:label];
    
    
    
    
    
    label.attributedText = [self LZSetString:@"¥0.00"];
    CGFloat maxWidth = LZSCREEN_WIDTH - selectAll.bounds.size.width - btn.bounds.size.width;
//    CGSize size = [label sizeThatFits:CGSizeMake(maxWidth, LZTabBarHeight)];
    label.frame = CGRectMake(CGRectGetMinX(btn.frame) - maxWidth , 5, maxWidth - 10, 25);
    label.textAlignment = NSTextAlignmentRight;
    self.totlePriceLabel = label;
    
    
    
    
    //是否含运费
    UILabel *yunfeiLB = [[UILabel alloc]init];
    yunfeiLB.font = kFont13;
    yunfeiLB.textColor = [UIColor grayColor];
    yunfeiLB.text = @"(含运费0元)";
    yunfeiLB.frame =CGRectMake( CGRectGetMinX(label.frame), CGRectGetMaxY(label.frame), CGRectGetWidth(label.frame), 15);
    yunfeiLB.textAlignment = NSTextAlignmentRight;
    [backgroundView addSubview:yunfeiLB];
    
    
    //结算按钮
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setBackgroundImage:[UIImage imageNamed:@"chengkuai"] forState:(UIControlStateNormal)];
    btn2.frame = CGRectMake(CGRectGetMinX(btn.frame)-120, 0, 120, LZTabBarHeight);
    [btn2 setTitle:@"删除" forState:UIControlStateNormal];
    btn2.hidden = YES;
    [backgroundView addSubview:btn2];
      [btn2 addTarget:self action:@selector(deleButtonClick2:) forControlEvents:UIControlEventTouchUpInside];
    _editOrCompleteBtn = btn2;
    
}

- (NSMutableAttributedString*)LZSetString:(NSString*)string {
    
    NSString *text = [NSString stringWithFormat:@"合计:%@",string];
    NSMutableAttributedString *LZString = [[NSMutableAttributedString alloc]initWithString:text];
    NSRange rang = [text rangeOfString:@"合计:"];
    [LZString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:rang];
    [LZString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16 *kScreen_Width/375] range:rang];
    return LZString;
}
#pragma mark -- 购物车为空时的默认视图
- (void)changeView {
    if (self.dataArray.count > 0) {
        UIView *view = [self.view viewWithTag:TAG_CartEmptyView];
        if (view != nil) {
            [view removeFromSuperview];
        }
        
        [self setupCartView];
    } else {
        UIView *bottomView = [self.view viewWithTag:TAG_CartEmptyView + 1];
        [bottomView removeFromSuperview];
        
        [self.myTableView removeFromSuperview];
        self.myTableView = nil;
        [self setupCartEmptyView];
    }
}

- (void)setupCartEmptyView {
    //默认视图背景
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, LZNaigationBarHeight, LZSCREEN_WIDTH, LZSCREEN_HEIGHT - LZNaigationBarHeight)];
    backgroundView.tag = TAG_CartEmptyView;
    [self.view addSubview:backgroundView];
    
    //默认图片
    UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:lz_CartEmptyString]];
    img.center = CGPointMake(LZSCREEN_WIDTH/2.0, LZSCREEN_HEIGHT/2.0 - 120);
    img.bounds = CGRectMake(0, 0, 247.0/187 * 100, 100);
    [backgroundView addSubview:img];
    
    UILabel *warnLabel = [[UILabel alloc]init];
    warnLabel.center = CGPointMake(LZSCREEN_WIDTH/2.0, LZSCREEN_HEIGHT/2.0 - 10);
    warnLabel.bounds = CGRectMake(0, 0, LZSCREEN_WIDTH, 30);
    warnLabel.textAlignment = NSTextAlignmentCenter;
    warnLabel.text = @"购物车为空!";
    warnLabel.font = [UIFont systemFontOfSize:15];
    warnLabel.textColor = LZColorFromHex(0x706F6F);
    [backgroundView addSubview:warnLabel];
    
}
#pragma mark  -=-=---=-=-=-=-=-=-=--- 购物车有商品时的视图
- (void)setupCartView {
    //创建底部视图
    [self setupCustomBottomView];
    
    UITableView *table = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    
    table.delegate = self;
    table.dataSource = self;
    table.showsVerticalScrollIndicator = NO;
    table.showsHorizontalScrollIndicator = NO;
    table.rowHeight = lz_CartRowHeight;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    table.backgroundColor = KShouYeBg;
    [self.view addSubview:table];
    self.myTableView = table;
    
    /*
    //添加下拉刷新;
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handleRefresh)];
    
    //添加上拉加载更多;
    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handleLoadMore)];
    */
    
    if (_isHasTabBarController) {
        table.frame = CGRectMake(0, LZNaigationBarHeight, LZSCREEN_WIDTH, LZSCREEN_HEIGHT - LZNaigationBarHeight - 2*LZTabBarHeight);
    } else {
        table.frame = CGRectMake(0, LZNaigationBarHeight, LZSCREEN_WIDTH, LZSCREEN_HEIGHT - LZNaigationBarHeight - LZTabBarHeight);
    }
    
    [table registerClass:[LZTableHeaderView class] forHeaderFooterViewReuseIdentifier:@"LZHeaderView"];
    
    

    
    
  
    
    
    
}
#pragma mark --- UITableViewDataSource & UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    LZShopModel *model = [self.dataArray objectAtIndex:section];
    return model.goodsArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LZCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LZCartReusableCell"];
    if (cell == nil) {
        cell = [[LZCartTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"LZCartReusableCell"];
    }
   
    
    LZShopModel *shopModel = self.dataArray[indexPath.section];
    LZGoodsModel *model = [shopModel.goodsArray objectAtIndex:indexPath.row];
    
    __block typeof(cell)wsCell = cell;
    
   
    [cell.tempSeBtn addTarget:self action:@selector(chooseGiugeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    

    
    
    //商品做加法
    [cell numberAddWithBlock:^(NSInteger number) {
        wsCell.lzNumber = number;
        model.count = number;
      
        //单个商品做加法调用方法
       // [self addOrCutBtnAction:indexPath];
        [shopModel.goodsArray replaceObjectAtIndex:indexPath.row withObject:model];
        if ([self.selectedArray containsObject:model]) {
            [self.selectedArray removeObject:model];
            [self.selectedArray addObject:model];
            [self countPrice];
    
        }
    }];
    
    
    
    //商品做减法
    [cell numberCutWithBlock:^(NSInteger number) {
        wsCell.lzNumber = number;
        model.count = number;
        //单个商品做减法调用方法
       // [self addOrCutBtnAction:indexPath];
        [shopModel.goodsArray replaceObjectAtIndex:indexPath.row withObject:model];
        
        //判断已选择数组里有无该对象,有就删除  重新添加
        if ([self.selectedArray containsObject:model]) {
            [self.selectedArray removeObject:model];
            [self.selectedArray addObject:model];
            [self countPrice];
            
        }
    }];
    
    
    //选择所有的
    [cell cellSelectedWithBlock:^(BOOL select) {
        
        model.select = select;
        if (select) {
            [self.selectedArray addObject:model];
        } else {
            [self.selectedArray removeObject:model];
        }
       
        
        [self verityAllSelectState];
        [self verityGroupSelectState:indexPath.section];
        
        [self countPrice];
    }];
    
    [cell reloadDataWithModel:model];
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    LZTableHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LZHeaderView"];
    LZShopModel *model = [self.dataArray objectAtIndex:section];
    NSLog(@">>>>>>%d", model.select);
    view.title = model.shopName;
    view.select = model.select;
    view.lzClickBlock = ^(BOOL select) {
        model.select = select;
        if (select) {
            
            for (LZGoodsModel *good in model.goodsArray) {
                good.select = YES;
                if (![self.selectedArray containsObject:good]) {
                    
                    [self.selectedArray addObject:good];
                }
            }
            
        } else {
            for (LZGoodsModel *good in model.goodsArray) {
                good.select = NO;
                if ([self.selectedArray containsObject:good]) {
                    
                    [self.selectedArray removeObject:good];
                }
            }
        }
        
        [self verityAllSelectState];
        
        [tableView reloadData];
        [self countPrice];
    };
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return LZTableViewHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 50)];
    bgV.backgroundColor = KShouYeBg;
    LZShopModel *model = [self.dataArray objectAtIndex:section];
    
    UILabel *countLB = [[UILabel alloc] initWithFrame:CGRectMake(0, 1, kScreen_Width, 49)];
    countLB.text = [NSString stringWithFormat:@"    重量 %@",model.sku_weight];
    countLB.textColor = [UIColor blackColor];
    countLB.font = kFont15;
        countLB.backgroundColor = [UIColor whiteColor];
    [bgV addSubview:countLB];
    
    return bgV;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除该商品?删除后无法恢复!" preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            LZShopModel *shop = [self.dataArray objectAtIndex:indexPath.section];
            LZGoodsModel *model = [shop.goodsArray objectAtIndex:indexPath.row];
            
            [shop.goodsArray removeObjectAtIndex:indexPath.row];
            //    删除
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
            if (shop.goodsArray.count == 0) {
                [self.dataArray removeObjectAtIndex:indexPath.section];
            }
            
            //判断删除的商品是否已选择
            if ([self.selectedArray containsObject:model]) {
                //从已选中删除,重新计算价格
                [self.selectedArray removeObject:model];
                [self countPrice];
            }
            
            NSInteger count = 0;
            for (LZShopModel *shop in self.dataArray) {
                count += shop.goodsArray.count;
            }
            
            if (self.selectedArray.count == count) {
                _allSellectedButton.selected = YES;
            } else {
                _allSellectedButton.selected = NO;
            }
            
            if (count == 0) {
                [self changeView];
            }
            
            //如果删除的时候数据紊乱,可延迟0.5s刷新一下
            [self performSelector:@selector(reloadTable) withObject:nil afterDelay:0.5];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:okAction];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }

}

#pragma mrak －＝－＝－＝－进入商品详情页
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LZShopModel *shopModel = self.dataArray[indexPath.section];
    LZGoodsModel *model = [shopModel.goodsArray objectAtIndex:indexPath.row];
    FenLeiDDetailViewController *feiL = [[FenLeiDDetailViewController alloc] init];
    feiL.hidesBottomBarWhenPushed = YES;
    feiL.goodsID = model.goodsID;
    [self.navigationController pushViewController:feiL animated:YES];
    
}

- (void)reloadTable {
    [self.myTableView reloadData];
}
#pragma mark -- 页面按钮点击事件
#pragma mark --- 返回按钮点击事件
- (void)backButtonClick:(UIButton*)button {
    if (_isHasNavitationController == NO) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark --- 全选按钮点击事件
- (void)selectAllBtnClick:(UIButton*)button {
    button.selected = !button.selected;
    
    //点击全选时,把之前已选择的全部删除
    for (LZGoodsModel *model in self.selectedArray) {
        model.select = NO;
    }
    
    [self.selectedArray removeAllObjects];
    
    if (button.selected) {
        
        for (LZShopModel *shop in self.dataArray) {
            shop.select = YES;
            for (LZGoodsModel *model in shop.goodsArray) {
                model.select = YES;
                [self.selectedArray addObject:model];
            }
        }
        
    } else {
        for (LZShopModel *shop in self.dataArray) {
            shop.select = NO;
        }
    }
    [self.myTableView reloadData];
    [self countPrice];
}
#pragma mark ---＝＝＝＝＝＝＝ 结算确认选择,提交订单按钮点击事件＝＝＝
- (void)goToPayButtonClick:(UIButton*)button {
    if (self.selectedArray.count > 0) {
        NSMutableArray *skuIdArr = [NSMutableArray array];
        for (LZGoodsModel *model in self.selectedArray) {
            NSLog(@">>%@>>>%ld",model.choseId,(long)model.count);
            [skuIdArr addObject:model.choseId];
            if ([model.store_nums intValue] == 0) {
                [MBProgressHUD showText:[NSString stringWithFormat:@"%@库存为0",model.goodsName]];
                return;
            }
            
        }
       
        TiJIaoDingDanViewController *vc = [[TiJIaoDingDanViewController alloc] init];
        vc.sku_id = [BasePublicClass returnStringFromDicOrArray:skuIdArr];
      
        vc.buy_type = @"cart";
        vc.buy_num = @"";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [MBProgressHUD showText:@"您还没选择任何商品进行结算"];
        
    }
    
}

#pragma mark －－－－编辑状态下确认删除－＝－＝－＝－＝－＝
- (void)deleButtonClick2:(UIButton *)sender {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
  
    //初始化一个存放选中商品skuid的容器
    NSMutableArray *chooseIDArray  = [NSMutableArray array];
    if (chooseIDArray) {
        [chooseIDArray removeAllObjects];
    }
    
    if (self.selectedArray.count > 0) {
        for (LZGoodsModel *model in self.selectedArray) {
            [chooseIDArray addObject:model.choseId];
        }
        
        NSArray *tempArray = [NSArray arrayWithArray:chooseIDArray];
        NSString *string = [tempArray componentsJoinedByString:@","];
        
          NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"sku_id_str":string,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        [HttpRequest postWithURLString:POST(Shop_CartDeletedCart) parameters:parameDic success:^(id responseObject) {
            if ([responseObject[@"ret"] intValue] != 200) {
                [MBProgressHUD showText:@"删除商品失败，请重新尝试"];
                return ;
            }
            NSString *str  = responseObject[@"data"][@"code"];
            if ([str intValue] != 0) {
                [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
                return;
            }else {
                
                [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
                [self loadData];//重新取数据
                
            }
        } failure:^(NSError *error) {
            
        }];
        
    } else {
        [MBProgressHUD showText:@"请选择商品进行删除"];
    }
}




#pragma mark    －＝－＝－＝验证勾选状态＝－＝－＝－
- (void)verityGroupSelectState:(NSInteger)section {
    // 判断某个区的商品是否全选
    LZShopModel *tempShop = self.dataArray[section];
    // 是否全选标示符
    BOOL isShopAllSelect = YES;
    for (LZGoodsModel *model in tempShop.goodsArray) {
        // 当有一个为NO的是时候,将标示符置为NO,并跳出循环
        if (model.select == NO) {
            isShopAllSelect = NO;
            break;
        }
    }
    
    LZTableHeaderView *header = (LZTableHeaderView *)[self.myTableView headerViewForSection:section];
    header.select = isShopAllSelect;
    tempShop.select = isShopAllSelect;
}


#pragma mark －＝－－＝－底部按钮的全选
- (void)verityAllSelectState {
    
    NSInteger count = 0;
    for (LZShopModel *shop in self.dataArray) {
        count += shop.goodsArray.count;
    }
    
    if (self.selectedArray.count == count) {
        _allSellectedButton.selected = YES;
    } else {
        _allSellectedButton.selected = NO;
    }
    
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark -=-=-=-=-=-==弹出规格按钮的代理事件,更新购物车规格视图的代理
//第一个弹出视图，如果有三种规格
-(void)sureThirdViewBtnAction:(UIButton *)sender BackArray:(NSArray *)backArr{
 
    //oldChooseID 本身的老的sku_id
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    FenLeiExistListModle *model = backArr[0];
    NSString *coutStr = backArr[1];
    NSString *allMoneyString = backArr[2];
    
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"used_sku_id":oldChooseID,@"new_sku_id":model.sku_id,@"new_num":backArr[1],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(Shop_CartUpdateCartSku) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"修改商品规格出错" timeLength:1.5];
            return ;
        }
        
        NSString *tempS = responseObject[@"data"][@"code"];
        if ([tempS intValue] != 0) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"] ];
            return;
        }
        
        
        
        [self loadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    [_customThirdView removeFromSuperview];
    
}
- (void)remoPopViewBtnAction :(UIButton *)sender {
    [_customThirdView removeFromSuperview];
}



#pragma mark －－－－－－－－－－－－－－－－－－－－－重新选择规格的按钮的点击事件
//重新选择规格按钮
- (void)chooseGiugeBtnAction:(UIButton *)sender {
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    LZCartTableViewCell *cell = (LZCartTableViewCell *)[[sender superview] superview];
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    LZShopModel *shopModel = self.dataArray[indexPath.section];
    LZGoodsModel *model = [shopModel.goodsArray objectAtIndex:indexPath.row];
    
    oldChooseID = model.choseId;//把老的sku'_id取出来
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"goods_id":model.goodsID,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(Shop_CartGetGoodsSku) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"获取商品规格出错" timeLength:1.5];
            return ;
        }
        if (_customThirdView) {
            [_customThirdView removeFromSuperview];
        }
        
      
            //选择规格视图
            _customThirdView  = [[CustomGgThirdView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreen_Height)];
            _customThirdView.delegate = self;
            [[UIApplication sharedApplication].keyWindow addSubview:_customThirdView];
             NSDictionary *dic = responseObject[@"data"];
            //规格种类列表
            _guigeArray = [FenLeiSelectListModle mj_objectArrayWithKeyValuesArray:dic[@"spec_select_list"]];
            //默认选中的规格
            NSDictionary *morendic = dic[@"one_sku_data"];
            _morenModle = [FenLeiExistListModle mj_objectWithKeyValues:morendic];
            _numsKindArray = [FenLeiExistListModle mj_objectArrayWithKeyValuesArray:dic[@"sku_list"]];
            
            // 选择规格view 赋值
            _customThirdView.array4 = _numsKindArray;
            _customThirdView.imgStr = dic[@"goods"][@"image"];
            _customThirdView.selectModle = _morenModle;
            _customThirdView.totalArray = _guigeArray.mutableCopy;
            
   
        
        
    } failure:^(NSError *error) {
        
    }];
    
}





@end
